package com.hu.bgp.server;

import java.util.UUID;

import com.hu.bgp.server.domain.Profile;
import com.hu.bgp.server.domain.Score;

import de.novanic.eventservice.client.event.domain.Domain;
import de.novanic.eventservice.client.event.domain.DomainFactory;

public class Player
{
	private GameServerContext gsc;
	private Profile profile;
	private UUID uuid;
	private Domain domain;
	private GameInstance currentGameInstance;

	public Player(GameServerContext gsc, Profile profile)
	{
		this.gsc = gsc;
		this.profile = profile;
		uuid = UUID.randomUUID();
		domain = DomainFactory.getDomain("player" + profile.getId());
	}

	public Profile getProfile()
	{
		return profile;
	}

	public String getUuidString()
	{
		return uuid.toString();
	}

	public Domain getDomain()
	{
		return domain;
	}

	public GameInstance getCurrentGameInstance()
	{
		return currentGameInstance;
	}

	public void setCurrentGameInstance(GameInstance currentGameInstance)
	{
		this.currentGameInstance = currentGameInstance;
	}

	public void joinGame(GameInstance instance)
	{
		if (currentGameInstance == instance)
		{
			System.out.println(String.format("Player.joinGame: player %s aka %s already in %s", profile.getName(), uuid.toString(), instance.getUuidString()));
			currentGameInstance.rejoinPlayer(this);
		}
		else
		{
			if (currentGameInstance != null)
			{
				currentGameInstance.ejectPlayer(this);
			}
			instance.joinPlayer(this);
			currentGameInstance = instance;
			System.out.println(String.format("Player.joinGame: player %s aka %s joined %s", profile.getName(), uuid.toString(), instance.getUuidString()));
		}
	}

	public void addScore(String scoreText)
	{
		Score score = new Score();
		score.setGameTypeAlias(currentGameInstance.getGameType().getAlias());
		score.setProfileId(getProfile().getId());
		score.setScoreText(scoreText);
		score.save(gsc.getPersistence());
	}
}
